﻿namespace FilePutter
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Collections.Generic;
    using System.Threading;
    using WhiteTiger.Common.Ziper;
    /// <summary>
    /// 分类整理这个目录下的直接文件， 
    /// TODO 子目录下的文件整理暂时不支持
    /// </summary>
    public class FilePutter
    {
        /// <summary>
        /// 任务 配置
        /// </summary>
        private Setting _Setting = Setting.SortedByDocType;
        /// <summary>
        /// 需要整理的目录
        /// </summary>
        public string FolderPath { get; set; }
        /// <summary>
        /// 每隔 多少秒， 整理一次
        /// </summary>
        public int Stop_For_Seconds { get; set; }
        /// <summary>
        /// 异步线程任务
        /// </summary>
        private Thread _Task = null;
        public FilePutter(Setting Setting)
        {
            this._Setting = Setting;
            Stop_For_Seconds = 200;
        }

        public void Start()
        {
            this._Task = new Thread(() =>
            {
                while (true)
                {
                    _RunTask();
                    Thread.Sleep(this.Stop_For_Seconds * 1000);
                }
            });
            this._Task.IsBackground = true;
            this._Task.Start();
        }
        public void Stop()
        {
            try
            {
                this._Task.Abort();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void _RunTask()
        {
            if (this._Setting == Setting.SortedByDocType)
            {
                this._SortedByDocType(this.FolderPath);
            }
        }

        #region 根据配置名称， 创建具体分类办法

        private void _SortedByDocType(string _FolderPath)
        {
            string[] tmpFiles = Directory.GetFiles(_FolderPath);
            if (tmpFiles != null && tmpFiles.Length > 0)
            {
                string strFileType = string.Empty;
                string strTempFolder = _FolderPath + Path.DirectorySeparatorChar + Guid.NewGuid().ToString();
                string strFileTypeFolder = string.Empty;

                //1. 分类移动文件 到以类型命名的文件夹中
                Dictionary<string, string> tmp_DocType_Folders = new Dictionary<string, string>();
                foreach (var file in tmpFiles)
                {
                    strFileType = file.Substring(file.LastIndexOf(".")+1);//windows 文件夹不能用 符号点 开头
                    strFileTypeFolder = strTempFolder + Path.DirectorySeparatorChar + strFileType;
                    if (!Directory.Exists(strFileTypeFolder))
                    {
                        Directory.CreateDirectory(strFileTypeFolder);
                    }
                    File.Move(file, strFileTypeFolder + Path.DirectorySeparatorChar + file.Substring(file.LastIndexOf("\\") + 1));

                    tmp_DocType_Folders[strFileType] = strFileTypeFolder;
                }

                //按照文件夹 压缩目录， 将压缩的文件移动到 Classified 目录中
                string strClassifiedFolderPath = _FolderPath + Path.DirectorySeparatorChar + "Classified";
                if (!Directory.Exists(strClassifiedFolderPath))
                {
                    Directory.CreateDirectory(strClassifiedFolderPath);
                }
                ZipHelper ziper = new ZipHelper();
                bool bFlag = false;
                foreach (string type in tmp_DocType_Folders.Keys)
                {
                    ziper.FolderName = tmp_DocType_Folders[type];
                    ziper.OutputZipFileName = ziper.FolderName + ".zip";
                    try
                    {
                        ziper.CreateZIP();
                        bFlag = true;
                    }
                    catch
                    {
                        bFlag = false;
                    }
                    finally
                    {
                        if (bFlag)
                        {
                            File.Move(ziper.OutputZipFileName, strClassifiedFolderPath + ziper.OutputZipFileName.Substring(ziper.OutputZipFileName.LastIndexOf("\\") + 1));
                            Directory.Delete(ziper.FolderName, true);
                        }
                        else
                        {
                            var files = Directory.GetFiles(ziper.FolderName);
                            if (files != null && files.Length > 0)
                            {
                                var tmp = from a in files
                                          from b in tmpFiles
                                          where b.IndexOf(a) > -1
                                          select new Dictionary<string, string>() { { a, b } };
                                foreach (var item in tmp)
                                {
                                    File.Move(item.ElementAt(0).Key, item.ElementAt(0).Value);
                                }
                            }
                        }
                    }
                }

                Directory.Delete(strTempFolder, true);

            }
        }

        #endregion 根据配置名称， 创建具体分类办法
    }
}
